package ua.yandex.prodcons.threads;

public class CircularBuffer {

    private String[] elements;
    private int head;
    private int tail;
    private int size;
    private int capacity;

    public CircularBuffer(int capacity) {
        this.elements = new String[capacity];
        for (int i = 0; i < capacity; i++) {
            elements[i] = " ";
        }
        this.capacity = capacity;
    }

    public void add(String data) {
        synchronized (this) {
            while (size == elements.length) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            size++;
            elements[tail = (tail + 1) % capacity] = data;
            notifyAll();
        }

    }

    public String remove() throws InterruptedException {
        synchronized (this) {
            while (size == 0) {
                wait();
            }
            String res = elements[head];
            head = (head + 1) % capacity;
            size--;
            notifyAll();
            return res;
        }
    }
}
